<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use App\Models\Menu;

class MenuController extends BaseController{
	
	public function getIndex(){
		$arr=Menu::all()->toArray();
		$iseditstr='';
        if (\Gate::check('chkaccess', 'App\Http\Controllers\MenuController@getEdit')) {
        	$iseditstr='-------------------<a href="javascript:void(0);" onclick="location.href=\'/menu/edit/$reeditstr\'">修改</a>';
        }
		$arrt=$this->getTreeview($arr,0,$iseditstr);

       

		$jsontv=json_encode($arrt);
		return view('menu.index')->with('jsontv',$jsontv);
	}

	public function getEdit($id){
		$menu=Menu::find($id);
		return view('menu.edit')->with('info',$menu);
	}

	public function postEdit(){
		$id=Input::get('id');
		$menu = Menu::find($id);
		$menu->name = Input::get('name');
        $menu->status_at = Input::get('status_at',0);
		$res=$menu->save();
		if($res){
			return redirect('tooltip/success')->with(['redirectway'=>'编辑成功！','redirecturl'=>'/menu/index']);
		}else{
			return redirect('tooltip/failure')->with(['redirectway'=>'编辑失败！','redirecturl'=>'/menu/index']);
		}
		
	}

	//获取jstree树形结构
	private function getTreeview($data,$pid=0,$iseditstr)
    {
        $tree = array();
        foreach($data as $k => $v)
        {
            if($v['pid'] == $pid){
            	$tmparr = array();
            	$tmparr['id']=$v['id'];
                $tmparr['text']=$v['name'].str_replace('$reeditstr',$v['id'],$iseditstr);
                $tmparr['state']=array('opened'=>true);
                $tmparr['children'] =$this->getTreeview($data,$v['id'],$iseditstr);
                $tree[] = $tmparr;
                unset($data[$k]);
           }
        }
        return $tree;
    }


}
